package com.xukehong.demo.util.encryption;

import com.alipay.api.internal.util.codec.Base64;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.FileUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.security.KeyStore;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.util.Enumeration;

/**
 * @Author: xkh
 * @Date: 2019/12/2 13:59
 * @Version 1.0
 */
public class CertUtil {

    public static String sign(String strPfx,String strPassword,String a) throws Exception {
        File pfxFile = new File(strPfx);
        KeyStore keystore = getKeyStore((FileUtils.readFileToByteArray(pfxFile)),strPassword);
        Enumeration<String> aliasenum = keystore.aliases();
        String keyAlias = null;
        if (aliasenum.hasMoreElements()) {
            keyAlias = aliasenum.nextElement();
        }
        RSAPrivateKey privateKey = (RSAPrivateKey) keystore.getKey(keyAlias,strPassword.toCharArray());
        Signature st = Signature.getInstance("SHA1withRSA");
        st.initSign(privateKey);
        st.update(a.getBytes(Charsets.UTF_8));
        byte[] result = st.sign();
        byte[] b = Base64.encodeBase64(result);
        String c = new String(b);
        return c;
    }

    private static KeyStore getKeyStore(byte[] pfxData, String password) throws Exception {
        KeyStore keystore = KeyStore.getInstance("PKCS12");
        keystore.load(new ByteArrayInputStream(pfxData), password.toCharArray());
        return keystore;
    }
}
